<?php

	class EbTemplate
	{		
		static public function includeTemplate($file)
		{
			$cachePath = EBUILDY_PATH.'cache/'.md5($file).'.php';

			if (true || !file_exists($cachePath))
			{
				$buffer = file_get_contents($file);
				
				$buffer = self::doEbuildyTemplate($buffer);
								
				file_put_contents($cachePath,$buffer);
			}
			
			include ($cachePath);die();
		}
		
		static public function doEbuildyTemplate($buffer)
		{
			$buffer = preg_replace('/#([^ #]*)#/','<?php echo ${1}; ?>',$buffer);
			$buffer = preg_replace('/echo ([a-z])/','echo $${1}',$buffer);
			
			$buffer = preg_replace('/<php:set (.*) [\/]*>/','<?php ${1}; ?>',$buffer);
			
			$buffer = preg_replace('/<php:if (.*)>/','<?php if (${1}): ?>',$buffer);
			$buffer = str_replace('</php:if>','<?php endif; ?>',$buffer);
			$buffer = str_replace('<php:else />','<?php else: ?>',$buffer);
			
			$buffer = str_replace('<php>','<?php ',$buffer);
			$buffer = str_replace('</php>',' ?>',$buffer);
			
			$buffer = preg_replace_callback('/<widget:([a-z]*) (.*) \/>/',"EbTemplate::toto",$buffer);
			
		//	ob_clean();die(htmlentities($buffer));
			return $buffer;
		}		
		
		static public function toto($matches)
		{			
			$buffer = str_replace(array("='",'="','" '),array(" => '",' => ',','),$matches[2]);
						
			//$buffer = preg_replace('/ ([^=]*)=([^"]*)/',"${1} => ${2},",' '.$matches[2]);
			
//			$buffer = $matches[2];
//			
//			$buffer = preg_replace('/="/',' => ',$buffer);
//			$buffer = preg_replace('/" /',',',$buffer);
			
			if ($buffer[strlen($buffer) - 1] == '"')
			{
				$buffer = substr($buffer,0,strlen($buffer) - 1);
			}
			
			ob_clean();die(htmlentities($matches[2]).' : '.htmlentities($buffer));
						
			return '<?php eb_widget("'.$matches[1].'",array('.$buffer.'));?>';
		}
		
		static public function doColdfusionTemplate($buffer)
		{
			$buffer = preg_replace('/#([^ #]*)#/','<?php echo ${1}; ?>',$buffer);
			$buffer = preg_replace('/echo ([a-z])/','echo $${1}',$buffer);
			
			$buffer = preg_replace('/<cfset (.*) [\/]*>/','<?php ${1}; ?>',$buffer);
			
			$buffer = preg_replace('/<cfif (.*)>/','<?php if (${1}): ?>',$buffer);
			$buffer = str_replace('</cfif>','<?php endif; ?>',$buffer);
			$buffer = str_replace('<cfelse>','<?php else: ?>',$buffer);
			
			$buffer = preg_replace('/<widget:([a-z]*) (.*) \/>/','<?php eb_widget("${1}",array(${2}));?>',$buffer);
			
			ob_clean();die(htmlentities($buffer));
			return $buffer;
		}
		
	}